package org.jeecg.modules.demo.caiWuSkd.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.aspect.annotation.PermissionData;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.demo.caiWuSkd.entity.CwSkd;
import org.jeecg.modules.demo.caiWuSkd.service.ICwSkdService;
import org.jeecg.modules.demo.cwSaleInvoice.entity.CwSaleInvoice;
import org.jeecg.modules.demo.cwSaleInvoice.service.ICwSaleInvoiceService;
import org.jeecg.modules.demo.soSaleOrder.entity.SoSaleOrder;
import org.jeecg.modules.demo.soSaleOrder.service.ISoSaleOrderService;
import org.jeecg.modules.demo.yxqcysOrder.entity.YxQcysOrder;
import org.jeecg.modules.demo.yxqcysOrder.service.IYxQcysOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.*;

/**
 * @Description: 收款单
 * @Author: jeecg-boot
 * @Date: 2021-12-14
 * @Version: V1.0
 */
@Api(tags = "收款单")
@RestController
@RequestMapping("/sale/cwSkd")
@Slf4j
public class CwSkdController extends JeecgController<CwSkd, ICwSkdService> {
    @Autowired
    private ICwSkdService cwSkdService;
    @Autowired
    private ICwSaleInvoiceService cwSaleInvoiceService;
    @Autowired
    private ISoSaleOrderService soSaleOrderService;
    @Autowired
    private ISysBaseAPI sysBaseAPI;
    @Autowired
    private IYxQcysOrderService iYxQcysOrderService;

    /**排序列*/
    private static final String ORDER_COLUMN = "column";
    /**排序方式*/
    private static final String ORDER_TYPE = "order";
    private static final String ORDER_TYPE_ASC = "ASC";
    private static final String ORDER_TYPE_DESC = "DESC";

    /**
     * 分页列表查询
     *
     * @param cwSkd
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "收款单-分页列表查询")
    @ApiOperation(value = "收款单-分页列表查询", notes = "收款单-分页列表查询")
    @GetMapping(value = "/list")
    @PermissionData(pageComponent="yunxiao/collection/CwSkdList")
    public Result<?> queryPageList(CwSkd cwSkd,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
       try{
           QueryWrapper<CwSkd> queryWrapper = QueryGenerator.initQueryWrapper(cwSkd, req.getParameterMap());
           queryWrapper.eq("IS_DELETE", 0);
           queryWrapper.and(wq -> wq
                   .eq("YW_TYPE", 1)
                   .or()
                   .eq("YW_TYPE", 5));
           Page<CwSkd> page = new Page<CwSkd>(pageNo, pageSize);
           IPage<CwSkd> pageList = cwSkdService.getList(page, queryWrapper);
           return Result.OK(pageList);
       }catch (Exception e){
           e.printStackTrace();
           return Result.error(300,"网络故障！");
       }
    }

    //预收款单
    @GetMapping(value = "/listYskd")
    @PermissionData(pageComponent="yunxiao/collection/CwYskdList")
    public Result<?> queryPageListYskd(CwSkd cwSkd,
                                       @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                       @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                       HttpServletRequest req) {
        QueryWrapper<CwSkd> queryWrapper = QueryGenerator.initQueryWrapper(cwSkd, req.getParameterMap());
        queryWrapper.eq("IS_DELETE", 0);
        queryWrapper.eq("YW_TYPE", 2);
        Page<CwSkd> page = new Page<CwSkd>(pageNo, pageSize);
        IPage<CwSkd> pageList = cwSkdService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    //期初预收款单list
    @GetMapping(value = "/qcYskdlist")
    @PermissionData(pageComponent="yunxiao/yxqcysOrder/QcYskdList")
    public Result<?> queryqcYskdlist(CwSkd cwSkd,
                                       @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                       @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                       HttpServletRequest req) {
        QueryWrapper<CwSkd> queryWrapper = QueryGenerator.initQueryWrapper(cwSkd, req.getParameterMap());
        queryWrapper.eq("IS_DELETE", 0);
        queryWrapper.eq("YW_TYPE", 6);
        Page<CwSkd> page = new Page<CwSkd>(pageNo, pageSize);
        IPage<CwSkd> pageList = cwSkdService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param
     * @return
     */
    //根据发票单生成收款单
    //生成收款单
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody JSONObject jsonObject, HttpServletRequest req) {
        if (cwSkdService.addSkd(jsonObject, req)) {
            return Result.OK("操作成功！");
        }
        return Result.error("操作失败!");

    }

    //根据期初应收款单生成收款单
    @PostMapping(value = "/addQcSkd")
    public Result<?> addQcSkd(@RequestBody JSONObject jsonObject, HttpServletRequest req) {

        if (cwSkdService.addQcSkd(jsonObject, req)) {
            return Result.OK("操作成功！");
        }
        return Result.error("操作失败!");

    }

    //生成预收款单
    @PostMapping(value = "/addYskd")
    public Result<?> addYskd(@RequestBody JSONObject jsonObject, HttpServletRequest req) {
        if (cwSkdService.addYskd(jsonObject, req)) {
            return Result.OK("添加成功！");
        }
        return Result.error("添加失败!");

    }

    //生成期初预收款单
    @PostMapping(value = "/addQcYskd")
    public Result<?> addQcYskd(@RequestBody JSONObject jsonObject, HttpServletRequest req) {
        if (cwSkdService.addQcYskd(jsonObject, req)) {
            return Result.OK("添加成功！");
        }
        return Result.error("添加失败!");

    }

    //查询预收款抵扣单
    @PostMapping(value = "/getYskdk")
    public String getYskdk(@RequestBody CwSkd cwSkd) {
        Gson gson = new Gson();
        Map map = new HashMap();
        try {
            List<CwSkd> skds = new ArrayList<>();
            CwSkd skd = cwSkdService.getByskNo(cwSkd.getSrNo());
            skds.add(skd);
            map.put("code", 200);
            map.put("message", "查询成功！");
            map.put("payorders", skds);
            String json = gson.toJson(map);
            return json;
        } catch (Exception e) {
            e.printStackTrace();
            map.put("code", 500);
            map.put("message", "系统错误！");
            String json = gson.toJson(map);
            return json;
        }
    }

    /**
     * 编辑普通收款单
     *
     * @param
     * @return
     */
    @AutoLog(value = "收款单-编辑")
    @ApiOperation(value = "收款单-编辑", notes = "收款单-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody CwSkd cwSkd) {
        if (cwSkdService.edit(cwSkd)) {
            return Result.OK("操作成功！");
        }
        return Result.error("操作失败!");
    }

    //预收款单编辑
    @PutMapping(value = "/editYsk")
    public Result<?> editYsk(@RequestBody CwSkd cwSkd) {
        SoSaleOrder sso = soSaleOrderService.getBysoNo(cwSkd.getSoNo());
        sso.setYskJine(sso.getYskJine().add(cwSkd.getBjJine()).subtract(cwSkd.getSkJinee()));
        soSaleOrderService.updateById(sso);
        cwSkd.setBjJine(cwSkd.getSkJinee());
        cwSkd.setSkJinen(cwSkd.getSkJinee());
//        cwSkd.setCreateTime(new Date());
        cwSkdService.updateById(cwSkd);
        return Result.OK("编辑成功!");
    }

    //审核弃审
    @PutMapping(value = "/editShenhe")
    public Result<?> editShenhe(@RequestBody CwSkd cwSkd) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if (!cwSkd.getShName().equals(sysUser.getId())) {
            return Result.error(300, "您不是当前单据的指定审核人！");
        }
        if (cwSkd.getSoStatus() == 1) {
//            cwSkd.setShName(sysUser.getRealname());
            cwSkd.setShTime(new Date());
        } else {
//            cwSkd.setShName("");
            cwSkd.setShTime(null);
        }
//        cwSkd.setCreateTime(new Date());
        cwSkdService.updateById(cwSkd);
        return Result.OK("编辑成功!");
    }


    //删除普通收款单/期初收款单
    @PutMapping(value = "/flaseDelete")
    public Result<?> flaseDelete(@RequestBody CwSkd cwSkd) {
        CwSaleInvoice c = cwSaleInvoiceService.getByInvoiceNo(cwSkd.getFpNo());
        YxQcysOrder qc = iYxQcysOrderService.getByQcskNo(cwSkd.getQcskNo());
        if (c!=null) {
            if ("1".equals(cwSkd.getSyys())) {
                CwSkd skd = cwSkdService.getByskNo(cwSkd.getSyyskNo());
                CwSkd sk = cwSkdService.getByskNo(cwSkd.getSrNo());
                cwSkdService.removeById(sk);
                skd.setSkJinen(skd.getSkJinen().add(cwSkd.getSyyskJine()));
                c.setSupamount(c.getSupamount().add(cwSkd.getSyyskJine()).add(cwSkd.getSkJinen()));
                c.setSyysJine(BigDecimal.valueOf(0));
                cwSkdService.updateById(skd);
            } else {
                    c.setSupamount(c.getSupamount().add(cwSkd.getSkJinen()));
            }

            c.setIsSkd(0);
            cwSaleInvoiceService.updateById(c);
        }

        if (qc != null){
            if ("1".equals(cwSkd.getSyys())) {
                CwSkd skd = cwSkdService.getByskNo(cwSkd.getSyyskNo());
                CwSkd sk = cwSkdService.getByskNo(cwSkd.getSrNo());
                cwSkdService.removeById(sk);
                skd.setSkJinen(skd.getSkJinen().add(cwSkd.getSyyskJine()));
                qc.setSurplusJine(qc.getSurplusJine().add(cwSkd.getSyyskJine()).add(cwSkd.getSkJinen()));
                cwSkdService.updateById(skd);
            }else {
                qc.setSurplusJine(qc.getSurplusJine().add(cwSkd.getSkJinen()));
            }
            iYxQcysOrderService.updateById(qc);
        }

        cwSkdService.removeById(cwSkd);
        return Result.OK("编辑成功!");
    }

    //退回预收款单
    @PutMapping(value = "/returnYsk")
    public Result<?> returnYs(@RequestBody CwSkd cwSkd) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if (!cwSkd.getShName().equals(sysUser.getId())) {
            return Result.error(300, "您不是当前单据的指定审核人！");
        }
        CwSaleInvoice csi = cwSaleInvoiceService.getByskNo(cwSkd.getSkNo());
        if (csi == null) {
            cwSkd.setSoStatus(3);
            SoSaleOrder sso = soSaleOrderService.getBysoNo(cwSkd.getSoNo());
            sso.setYskJine(sso.getYskJine().subtract(cwSkd.getSkJinen()));
            soSaleOrderService.updateById(sso);
            cwSkdService.updateById(cwSkd);
        } else {
            return Result.error("此预收款单已被发票单" + csi.getInvoiceNo() + "使用预收，不能退回!");
        }
        return Result.OK("退回预收款单成功!");
    }

    //删除预收款单
    @PutMapping(value = "/flaseDeleteYsk")
    public Result<?> flaseDeleteYsk(@RequestBody CwSkd cwSkd) {
        CwSaleInvoice c = cwSaleInvoiceService.getByskNo(cwSkd.getSkNo());
        if (c == null) {
            if (cwSkd.getSoStatus() != 3) { //!=已退回状态
                SoSaleOrder sso = soSaleOrderService.getBysoNo(cwSkd.getSoNo());
                sso.setYskJine(sso.getYskJine().subtract(cwSkd.getSkJinen()));
                soSaleOrderService.updateById(sso);
                cwSkdService.removeById(cwSkd);
            } else {
                cwSkdService.removeById(cwSkd);
            }

        } else {
            return Result.error("此预收款单已被发票单" + c.getInvoiceNo() + "使用预收，不能删除!");
        }
        return Result.OK("删除成功!");
    }


    @GetMapping(value = "/getByskNo")
    public Result<?> getByskNo(@RequestParam(name = "skNo", required = true) String skNo) {
        CwSkd cwSkd = cwSkdService.getByskNo(skNo);
        return Result.OK(cwSkd);
    }

    //发票单页面查询预收款总金额、剩余、已使用金额
    @GetMapping(value = "/getYskBytradecode")
    public String getYskBytradecode(@RequestParam(name = "tradecode", required = true) String tradecode) {
        Gson gson = new Gson();
        Map map = new HashMap();
        try{
            Map<String,Double> stringDoubleMap = cwSkdService.getYskBytradecode(tradecode);
            map.put("yszje",stringDoubleMap.get("YSKJE"));
            map.put("syje",stringDoubleMap.get("SYJE"));
            map.put("useje",stringDoubleMap.get("USEJE"));
            String json = gson.toJson(map);
            return json;
        }catch (Exception e){
            e.printStackTrace();
            map.put("code",500);
            map.put("message","系统错误！");
            String json = gson.toJson(map);
            return json;
        }

    }
    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "收款单-通过id删除")
    @ApiOperation(value = "收款单-通过id删除", notes = "收款单-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        cwSkdService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "收款单-批量删除")
    @ApiOperation(value = "收款单-批量删除", notes = "收款单-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.cwSkdService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "收款单-通过id查询")
    @ApiOperation(value = "收款单-通过id查询", notes = "收款单-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        CwSkd cwSkd = cwSkdService.getById(id);
        if (cwSkd == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(cwSkd);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param cwSkd
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, CwSkd cwSkd) {
        return super.exportXls(request, cwSkd, CwSkd.class, "收款单");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, CwSkd.class);
    }



}
